package com.ld.oauth2.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ld.oauth2.mapper.SysUserMapper;
import com.ld.oauth2.model.bo.RegisterUser;
import com.ld.oauth2.model.po.SysUser;
import com.ld.oauth2.service.SysUserService;
import com.ld.oauth2.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * ServiceImpl<M extends BaseMapper<T>, T> 是对 IService接口中方法的实现
 * 第1个泛型 M 指定继承了 BaseMapper接口的子接口
 * 第2个泛型 T 指定实体类
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public SysUser findByUsername(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        // baseMapper 对应的是 SysUserMapper 实例
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public SysUser findByMobile(String mobile) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        // baseMapper 对应的是 SysUserMapper 实例
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public void register(RegisterUser registerUser) {
        String encodePassword = passwordEncoder.encode(registerUser.getPassword());
        SysUser sysUser = new SysUser();
        sysUser.setUsername(registerUser.getUsername());
        sysUser.setPassword(encodePassword);
        baseMapper.insert(sysUser);
    }

    @Override
    public Map<String, Object> refresh(String refreshToken) {
        Map<String, Object> result = getResultMap(refreshToken);
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal != null && principal instanceof UserDetails) {
            SysUser userInfo = (SysUser) principal;
            result.put("userInfo", userInfo);
        }
        return result;
    }

    /**
     * 远程调用刷新token
     * @param refreshToken
     * @return
     */
    private Map<String, Object> getResultMap(String refreshToken) {
        Map<String, Object> result = new HashMap<String, Object>();
        String authenHeader = HttpUtil.getAuthenHeader();
        System.out.println(authenHeader);
        String url = "http://127.0.0.1:8000/auth/oauth/token";
        Map<String, Object> params = new HashMap<String, Object>();
        Map<String, String> reqHeader = new HashMap<String, String>();
        try {
            params.put("grant_type", "refresh_token");
            params.put("refresh_token", refreshToken);
            reqHeader.put("Authorization", authenHeader);
            String str = HttpUtil.postUrlAsString(url, params, reqHeader);
            JSONObject jsonObject = JSON.parseObject(str);
            String access_token = (String) jsonObject.get("access_token");
            String token_type = (String) jsonObject.get("token_type");
            String refresh_token = (String) jsonObject.get("refresh_token");
            Integer expires_in = (Integer) jsonObject.get("expires_in");
            String scope = (String) jsonObject.get("scope");
            String jti = (String) jsonObject.get("jti");
            result.put("access_token", access_token);
            result.put("token_type", token_type);
            result.put("refresh_token", refresh_token);
            result.put("expires_in", expires_in);
            result.put("scope", scope);
            result.put("jti", jti);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


}
